<template>
  <div>
    <el-upload
      ref="uploadRef"
      v-model:file-list="files"
      :auto-upload="false"
      :limit="limit"
      :on-success="submitFormSuccess"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-preview="handlePreview"
      :on-change="handleChange"
      drag
      :on-remove="handleRemove"
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <span>
            大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
          </span>
          <span>
            个数不超过 <b style="color: #f56c6c">{{ limit }}个</b>
          </span>
        </div>
      </template>
    </el-upload>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'DefectUpload' })
import { ref } from 'vue'
import { propTypes } from '@/utils/propTypes'
const message = useMessage() // 消息弹窗
const emit = defineEmits(['success'])
const files = ref([] as any)
const uploadRef = ref()
const props = defineProps({
  limit: propTypes.number.def(5), // 数量限制
  fileList: propTypes.array.def([]),
  fileSize: propTypes.number.def(16), // 大小限制(MB)
  pasteImg: propTypes.array.def([])
})

watch(
  () => props.fileList,
  () => {
    nextTick(() => {
      files.value = props.fileList
    })
  },
  {
    deep: true,
    immediate: true
  }
)

const submitFormSuccess = () => {
  message.success('上传成功')
}
const submitFormError = () => {
  message.error('导入数据失败，请您重新上传！')
}

const handleExceed = (file) => {
  message.error(`上传文件数量不能超过${props.limit}个!`)
}
const handleRemove = (file, files) => {
  emit('success', files)
}
const handleChange = (file, files) => {
  const length = props.pasteImg.length + files.length
  const isLimit = file.size < props.fileSize * 1024 * 1024
  if (!isLimit) {
    message.error(`上传文件大小不能超过${props.fileSize}MB!`)
    files.pop()
    return false
  }
  if (length > 5) {
    message.error(`上传文件数量不能超过${props.limit}个!`)
    files.pop()
    return false
  }
  emit('success', files)
}

const handlePreview = async (file) => {
  const url = file.url
  if (!url) {
    message.warning('无链接')
    return
  }
  window.open(`${url}`, '_blank')
}

onMounted(() => {
  uploadRef.value.clearFiles()
  nextTick(() => {
    files.value = props.fileList
  })
})
</script>

<style scoped>
:deep(.el-icon--close-tip) {
  display: none !important;
}
</style>
